package top.shaoxia.pwdm.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.shaoxia.pwdm.pojo.PwdmDetailsDO;
import top.shaoxia.pwdm.pojo.PwdmFolderDO;
import top.shaoxia.pwdm.repositories.PwdmDetailsRepository;
import top.shaoxia.pwdm.repositories.PwdmFolderRepository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author wjc
 * @date 2022/2/19
 */
@Service
@Transactional
public class PwdmFolderService {
    @Autowired
    private PwdmFolderRepository pwdmFolderRepository;
    @Autowired
    private PwdmDetailsRepository pwdmDetailsRepository;

    public List<PwdmFolderDO> listAllFolders() {
        Iterable<PwdmFolderDO> all = pwdmFolderRepository.findAll();
        List<PwdmFolderDO> list = new ArrayList<>();
        all.forEach(list::add);
        return list;
    }

    public PwdmFolderDO insert(PwdmFolderDO folderDO) {
        return pwdmFolderRepository.save(folderDO);
    }

    public void delete(PwdmFolderDO folderDO) {
        pwdmFolderRepository.delete(folderDO);
        //查询该文件夹下的数据，将他们的folderId清空后保存
        List<PwdmDetailsDO> detailsDOList = pwdmDetailsRepository.findByFolderIdOrderBySnDesc(folderDO.getId());
        detailsDOList.forEach(d -> d.setFolderId(null));
        pwdmDetailsRepository.saveAll(detailsDOList);
    }

    public PwdmFolderDO selectById(PwdmFolderDO folderDO) {
        Optional<PwdmFolderDO> byId = pwdmFolderRepository.findById(folderDO.getId());
        return byId.get();
    }
}
